package com.junsi.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.junsi.bean.Client;
import com.junsi.bean.Communal;
import com.junsi.bean.Contact;
import com.junsi.bean.Department;
import com.junsi.bean.Information;
import com.junsi.bean.Staff;
import com.junsi.service.ClientService;
import com.junsi.service.CommunalService;
import com.junsi.service.ContactService;
import com.junsi.service.DepartmentSerivce;
import com.junsi.service.InformationService;
import com.junsi.service.StaffSerivce;
import com.junsi.util.ContactUtil;
import com.junsi.util.InteractiveUtil;
import com.junsi.util.PageUtil;

/**   
  * @文件名: ContactController.java 
  * @包名: com.junsi.controller 
  * @类名: ContactController   
  * @时间: 2017年7月19日 上午10:47:03 2017
  * @作者: 
  * @类功能描述:TODO 联系人控制层   
  */
@Controller
@RequestMapping("/contact")
public class ContactController {

	@Autowired
	private ContactService contactService;
	
	@Autowired
	private InformationService informationService;
	
	@Autowired
	private StaffSerivce staffSerivce;
	
	@Autowired
	private DepartmentSerivce departmentSerivce;
	
	@Autowired
	private CommunalService communalService;
	
	@Autowired
	private ClientService clientService;
	
	
	Logger logger=Logger.getRootLogger();
	

	/**
	 * 新增联系人
	 * @param contact
	 * @return
	 */
	@RequestMapping("/save")
	public void save( Contact contact,Information information,HttpServletResponse response,HttpServletRequest request){
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		Communal communal = new Communal();
		communal.setCommunal_creater(staff.getStaff_name());
		communal.setCommunal_amendName(staff.getStaff_name());
		communal.setCommunal_creationDate(new Date());
		boolean c = communalService.save(communal);
		if(c){
			boolean i =informationService.save(information);
			if(i){
				contact.setStaffID(staff.getStaff_id());
				contact.setDepartmentID(staff.getStaff_departmentId());
				contact.setCommunalID(communal.getCommunal_id());
				contact.setInformationID(information.getInformation_id());
				boolean b = contactService.save(contact);
				if(b){
					InteractiveUtil.WriteStringForHtml("新增成功", response);
					return;
				}
			}
		}
		InteractiveUtil.WriteStringForHtml("新增失败", response);
		
	}
	
	
	
	/**
	 * 根据id删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteById")
	public String deleteById(Integer id){
		if(id != null){
			Boolean result = contactService.deleteById(id);
			if(result){
				return "删除成功";
			}else{
				return "删除失败";
			}			
		}else{
			return "删除失败";
		}
	}
	
	/**
	 * 批量删除
	 * @param id
	 * @return
	 */
	@RequestMapping("deleteManyId")
	public void deleteManyId(String id,HttpServletResponse response){	
		
		if(id != null){
			String[] ids = id.split(",");
			boolean b = contactService.deletes(ids);
			if(b){
				InteractiveUtil.WriteStringForHtml("删除成功", response);
			}
		}
		InteractiveUtil.WriteStringForHtml("删除失败", response);
		
		
	}
	
	
	
	
	/**
	 * 修改
	 * @param client
	 * @return
	 */
	@RequestMapping("/update")
	public void update(HttpServletResponse response, Contact contact){
		Boolean result = contactService.update(contact);
		String s = null;
		if(result){
			s = "{'errorMsg':'true'}";
		}else {
			s = "{'errorMsg':'false'}";
		}
		try{
			response.getWriter().write(s);
			response.getWriter().flush();
			response.getWriter().close();
		}catch(IOException e){
			logger.error("传输更新失败");
			e.printStackTrace();
		}
				
	}
	
	
	
	
	/**
	 * 根据id查询客户信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/findById")
	public ModelAndView findById(Integer id, Model model){
		ModelAndView modelAndView = new ModelAndView();
		Contact contact = contactService.findById(id);
			ContactUtil contactUtil = new ContactUtil();
			contactUtil.setContact(contact);
			Information information = informationService.findById(contactUtil.getContact().getInformationID());
			//Department department = departmentSerivce.findById(contactUtil.getContact().getDepartmentID());	
			Communal communal = communalService.findById(contactUtil.getContact().getCommunalID());
			//Staff staff = staffSerivce.findById(contactUtil.getContact().getStaffID());
			Client client = clientService.findById(contactUtil.getContact().getClientID());
						
			contactUtil.setInformation(information.getInformation_phone());
			contactUtil.setCommunal(communal.getCommunal_creationDate());
			contactUtil.setClient(client.getClient_name());
		modelAndView.addObject("list", contactUtil);
		modelAndView.setViewName("");
		return modelAndView;
	}
	
	/**
	 * 查询所有联系人信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/findByAll")
	public ModelAndView findByAll(Integer id, PageUtil page,HttpServletRequest request){
		ModelAndView modelAndView = new ModelAndView();
		Integer number = contactService.findByNumber();
		if(number != null){
			page.setRowCount(number);
			List<Contact> contacts = contactService.findByPage(id, page.getEndIndex(), page.getBeginIndex());
			List<ContactUtil> contactUtils = new ArrayList<>();
		for(Contact contact : contacts){
			ContactUtil contactUtil = new ContactUtil();
			contactUtil.setContact(contact);
			contactUtils.add(contactUtil);
		}
		int i = 0;
		for(ContactUtil contactUtil : contactUtils){
			Staff staff = staffSerivce.findById(contactUtil.getContact().getStaffID());
			Department department = departmentSerivce.findById(contactUtil.getContact().getStaffID());			
			Information information = informationService.findById(contactUtil.getContact().getInformationID());
			Communal communal = communalService.findById(contactUtil.getContact().getCommunalID());
			if(staff == null || department == null || information == null || communal == null){
				continue;
			}
			contactUtils.get(i).setStaff(staff.getStaff_name());
			contactUtils.get(i).setDepartment(department.getDepartment_name());
			contactUtils.get(i).setInformation(information.getInformation_phone());
			contactUtils.get(i).setCommunal(communal.getCommunal_creationDate());
			i++;
		}
		
		//显示新增
		List<Client> client=clientService.findByAll();
 		List<Department> departments=departmentSerivce.findByAll();
 		request.getSession().setAttribute("client", client);
 		request.getSession().setAttribute("departments", departments);
		
		modelAndView.addObject("list", contactUtils);
		modelAndView.setViewName("forward:/contact/html/connector.jsp");
		
		}
		return modelAndView;
	}
	
	
	
	
	/**
	 * 分页查询
	 * @param id
	 * @return
	 */
	@RequestMapping("/findByPage")
	public void findByPage(Integer id,PageUtil page,HttpServletResponse response){		
		if(id != null){
			Integer number = staffSerivce.findByDepartmentNum(id);
			if(number != null){
				page.setRowCount(number);
				List<Staff> list = staffSerivce.findByDepartment(id, page.getEndIndex(), page.getBeginIndex());
				if(list != null){
					InteractiveUtil.WriteJsonForPage(list, page, response);
				}else{
					InteractiveUtil.WriteStringForHtml("失败", response);
				}
			}
		}else{
			InteractiveUtil.WriteStringForHtml("失败", response);
		}
		
	}
	
	/**
	 * 进入联系人页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/page")
	public ModelAndView page(HttpServletRequest request){
		ModelAndView modelAndView = new ModelAndView();
		Staff staff2 = (Staff)request.getSession().getAttribute("staff");
		modelAndView.addObject("staff", staff2);
		String staffs = (String)request.getSession().getAttribute("staffs");
		String[] ids = staffs.split(",");
		List<Contact> contacts = contactService.findByAll(ids);
		List<ContactUtil> contactUtils = new ArrayList<>();
		for (Contact contact : contacts) {
			ContactUtil contactUtil = new ContactUtil();
			if(contact.getClientID() != null){
				Client client = clientService.findById(contact.getClientID());
				if(client != null && client.getClient_id() != null)
				contactUtil.setClient(client.getClient_name());
			}
			if(contact.getStaffID() != null){
				Staff staff = staffSerivce.findById(contact.getStaffID());
				if(staff != null && staff.getStaff_id() != null)
				contactUtil.setStaff(staff.getStaff_name());
			}
			if(contact.getCommunalID() != null){
				Communal communal = communalService.findById(contact.getCommunalID());
				if(communal != null && communal.getCommunal_id() != null)
				contactUtil.setCommunal(communal.getCommunal_creationDate());
			}
			if(contact.getInformationID() != null){
				Information information = informationService.findById(contact.getInformationID());
				if(information != null && information.getInformation_id() != null)
				contactUtil.setInformation(information.getInformation_phone());
			}
			
			contactUtil.setContact(contact);
			contactUtils.add(contactUtil);
		}
		modelAndView.addObject("contactUtils", contactUtils);
		Department department = departmentSerivce.findById(staff2.getStaff_departmentId());
		modelAndView.addObject("department", department);
		List<Client> clients = clientService.findByAlls(ids);
		modelAndView.addObject("clients", clients);
		List<Staff> staff = staffSerivce.findByAll();
		modelAndView.addObject("staffList", staff);
		modelAndView.setViewName("forward:/html/connector.jsp");
		return modelAndView;
	}
	
	@RequestMapping(value="/updates")
	public void updates(String contact_id,String staff_id,HttpServletResponse response){
		if(contact_id != null && staff_id != null){
			String[] id = contact_id.split(",");
			boolean b = contactService.updates(staff_id,id);
			if(b){
				InteractiveUtil.WriteStringForHtml("修改成功", response);
				return;
			}
		}
		InteractiveUtil.WriteStringForHtml("修改失败", response);
	}
	
	@RequestMapping("/findByIds")
	public ModelAndView findById(Integer contact_id,HttpServletRequest request){
		ModelAndView modelAndView = new ModelAndView();
		Contact contact = contactService.findById(contact_id);
		Staff staff = staffSerivce.findById(contact.getStaffID());
		Client client = clientService.findById(contact.getClientID());
		Department department = departmentSerivce.findById(contact.getDepartmentID());
		Information information = informationService.findById(contact.getInformationID());
		Communal communal = communalService.findById(contact.getCommunalID());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");//
		Map<String,String> map=new HashMap<>();
		map.put("contact_id", String.valueOf(contact.getContact_id()));
		map.put("communalID", String.valueOf(contact.getCommunalID()));
		map.put("informationID", String.valueOf(contact.getInformationID()));
		if(client != null){
			map.put("client_name", client.getClient_name());
		}
		map.put("contact_job", contact.getContact_job());
		map.put("contact_cellphone", contact.getContact_cellphone());
		map.put("contact_email", contact.getContact_email());
		map.put("staff_name", staff.getStaff_name());
		map.put("contact_type", contact.getContact_type());
		map.put("contact_name", contact.getContact_name());
		map.put("contact_sex", contact.getContact_sex());
		map.put("department_name", department.getDepartment_name());
		String communalDate=null;
		 if(communal.getCommunal_creationDate()!=null){
			 communalDate=sdf.format(communal.getCommunal_creationDate());
		 }
		map.put("communal_creationDate", communalDate);
		map.put("communal_creater", communal.getCommunal_creater());				
		String amendDate = null;		
		if (communal.getCommunal_amendDate() != null) {
			amendDate = sdf.format(communal.getCommunal_amendDate());
		}
		map.put("communal_amendDate", amendDate);
		map.put("communal_amendName", communal.getCommunal_amendName());
		map.put("communal_remarks", communal.getCommunal_remarks());
		map.put("information_phone", information.getInformation_phone());
		map.put("contact_cellphone", contact.getContact_cellphone());	
		map.put("information_microblog", information.getInformation_microblog());
		map.put("information_province", information.getInformation_province());
		map.put("information_address", information.getInformation_address());
		map.put("information_postalcode", information.getInformation_postalcode());
		map.put("information_province", information.getInformation_province());
		map.put("information_city", information.getInformation_city());
		map.put("information_area", information.getInformation_area());
		
		//显示新增
		String ids = (String)request.getSession().getAttribute("staffs");
		String[] id = ids.split(",");
		List<Client> client1=clientService.findByAlls(id);
		List<Department> departments1 = departmentSerivce.findByAll();
		
		modelAndView.addObject("client1", client1);
		modelAndView.addObject("departments1", departments1);
		modelAndView.addObject("list", map);
		
		modelAndView.setViewName("forward:/html/connector1.jsp");//跳转页面
		return modelAndView;
		
	}
	/**
	 * 联系人详情页面编辑
	 */
	@RequestMapping("/updatecontact")
	@ResponseBody
	public void updatecontact( Contact contact,Information information,Communal communal,HttpServletResponse response,HttpServletRequest request){
		
		if(contact.getContact_id() != null){
			boolean c = true;
			if(communal.getCommunal_id() != null){
				Staff staff = (Staff)request.getSession().getAttribute("staff");
				communal.setCommunal_amendName(staff.getStaff_name());
				communal.setCommunal_amendDate(new Date());
				c = communalService.update(communal);
			}
			boolean i = true;
			if(information.getInformation_id() != null){
				if(information.getInformation_city() == null || information.getInformation_city() == ""){
					information.setInformation_city(null);
				}
				if(information.getInformation_province() == null || information.getInformation_province() == ""){
					information.setInformation_province(null);
				}
				if(information.getInformation_area() == null || information.getInformation_area() == ""){
					information.setInformation_area(null);
				}
				i = informationService.update(information);
			}
			if(i && c){
				boolean b = contactService.update(contact);
				if(b){
					InteractiveUtil.WriteStringForHtml("修改成功", response);
					return;
				}
			}
		}
		InteractiveUtil.WriteStringForHtml("修改失败", response);
		
	}

}
